<script setup>
  import { ref } from 'vue'
  import { onLoad, onShow, onUnload, onHide } from '@dcloudio/uni-app'
  import { http } from '@/utils/http.js'
  import { useUsercodeStore } from '@/store/usercode.js'
  import oneCard from './components/oneCard.vue'
  import threeCard from './components/threeCard.vue'
  import tenCard from './components/tenCard.vue'
  import PayBox from '../../components/PayBox.vue'
  import Progress from '../../components/progress.vue'
  import Api from './api/index.js'
  const __Api = new Api()
  const createOrderUrl = ref('createBoxOrder')
  // 创建 Store 实例

  const bginfo = ref('pink-bg')
  const cardsnum = ref()
  const is_flip = ref()
  const boxId = ref()
  const pay_type = ref()
  const caseId = ref()
  // 优惠Id
  const couponId = ref(0)
  const couponname = ref('')

  const paymoney = ref()
  const haveDraw = ref()
  const drawName = ref()
  const drawImg = ref()
  const energy_info = ref({})
  // 五秒关闭视频
  const showvideo = ref(false)
  const canBack = ref(true)
  const is_integral = ref()
  function backto() {
    uni.navigateBack({ delta: 1 })
  }
  function canClickFun() {
    // uni.navigateBack({ delta: 1 })
    canBack.value = true
  }
  const secondTimer = ref()
  //png序列
  let chuanshuo = ref('https://ojqn.wm2177.com/wechat_imgs/wx/cs/cs_00000.png')

  // 无限
  const rewardVideo = ref('https://ojqn.wm2177.com/wechat_imgs/smallvideo.mp4')

  function goRealName() {
    namepopup.value.open('center')
    uni.navigateTo({
      url: '/minePage/authentication/index',
    })
  }
  const namepopup = ref()

  function payReturnFun(res) {
    if (res.st == 1) {
      boxMineDetail()
      if (res.data.is_flip == 1) {
        // 狂欢模式
        canBack.value = false
      }
      if (res.data.is_flip == 0) {
        canBack.value = true
      }
      showAgainFun(res)
      paypopup.value.close()
    } else if (res.st == -2) {
      namepopup.value.open('center')
    } else {
      uni.utils.toast(res.msg)
    }
  }

  async function showAgainFun(res) {
    const userCodeStore = useUsercodeStore()
    // setTimeout(() => {
    //   payAgain.value = true
    // }, 2000)
    if (res.st == 1) {
      secondShow.value = false
      energy_info.value = res.data.energy_info
      orderId.value = res.data.order_id
      is_flip.value = res.data.is_flip
      secondShow.value = true
      haveDraw.value = res.data.box_goods

      // energy_info.value = true
      for (let i = 0; i < haveDraw.value.length; i++) {
        // console.log('抽到传说，抽到传说抽到传说抽到传说,上一个页面回调')
        const rule_id = haveDraw.value[i].rule_id
        if (rule_id == 1 || rule_id == 2) {
          wxvibrateLong(rule_id)
          rewardVideo.value = `https://ojqn.wm2177.com/wechat_imgs/${
            rule_id == 1 ? 'drawvideo' : 'smallvideo'
          }.mp4`
          if (userCodeStore.usercode.animation == 1) {
            showvideo.value = true
          }
          if (rule_id == 1) {
            // console.log('抽到传说，抽到传说抽到传说抽到传说,上一个页面回调')
          }
          return
        }
      }
    } else if (res.st == -2) {
      namepopup.value.open('center')
    } else {
      uni.utils.toast(res.msg)
      setTimeout(() => {
        backto()
      }, 3000)
    }
  }

  // 支付
  const paypopup = ref()
  // 优惠券之后的价格
  const realmoney = ref()
  const buyCount = ref(0)
  const agree = ref(true)
  const payAgain = ref(false)
  async function payPOP() {
    if (payAgain.value) {
      payAgain.value = false
      // await getUserMoney()
      secondShow.value = false
      // 每次点击重新选择优惠券
      realmoney.value = paymoney.value
      couponId.value = 0
      couponname.value = ''
      paypopup.value.open('bottom')
      // paymoney.value = (boxDetailInfo.value.price * cardsnum.value).toFixed(2)
    } else {
      uni.utils.toast('太快了，等等~')
    }
  }
  function changePop(e) {
    if (!e.show) {
      console.log('重置按钮')
      // setTimeout(() => {
      payAgain.value = true
      // }, 1000)
    }
  }
  function changeAgree() {
    agree.value = !agree.value
  }

  function radioChange(evt) {
    pay_type.value = evt.detail.value
  }

  // 获取订单id
  const orderId = ref()

  // 微信支付
  //轮询微信支付订单状态
  const timeStatu = ref(true)
  const paying = ref(1)

  //支付抽卡
  const secondShow = ref(true)

  // 用户信息星石(暂时)
  const balance = ref(0)
  const preferential = ref()
  // async function getUserMoney() {
  //   const res = await http.request({
  //     url: '/api/user/userMsg',
  //     method: 'POST',
  //     data: {},
  //   })
  //   balance.value = res.data.data.balance
  //   preferential.value = res.data.preferential
  // }

  // 选择优惠券
  function chooseCoupon() {
    uni.navigateTo({
      url: `/drawPage/choosecoupon/index?money=${paymoney.value}&id=${boxId.value}&couponid=${couponId.value}`,
    })
  }

  function goRule(id) {
    uni.navigateTo({
      url: `/homePage/agreement/index?id=${id}`,
    })
  }
  function wxvibrateLong(rule_id) {
    uni.vibrateLong({
      success: function () {
        // console.log('success')
      },
    })
    if (rule_id == 1) {
      setTimeout(() => {
        uni.vibrateLong({
          success: function () {
            // console.log('success')
          },
        })
      }, 500)
    }
  }
  const shebei = ref(process.env.VUE_APP_PLATFORM)

  const payGoodId = ref()
  const payGoodImg = ref()
  onLoad((option) => {
    const userCodeStore = useUsercodeStore()
    // switchNum.value = option.switchNum
    // gameStatus.value = option.status
    // game_id.value = option.game_id
    if (option.status == 0) {
      // 未开始
      switchFun()
    }
    if (option.status == 1) {
      // 进行中
      gamingFun()
    }
    payAgain.value = false
    setTimeout(() => {
      payAgain.value = true
    }, 500)
    secondShow.value = true
    cardsnum.value = option.num
    is_flip.value = option.is_flip
    if (is_flip.value == 1) {
      canBack.value = false
    }
    boxId.value = option.id
    pay_type.value = option.pay_type
    caseId.value = option.case_id
    paymoney.value = option.money
    drawName.value = option.name
    drawImg.value = option.img
    couponId.value = option.couponid
    orderId.value = option.order_id
    payGoodId.value = option.payGoodId
    payGoodImg.value = option.payGoodImg
    is_integral.value = option.is_integral
    haveDraw.value = JSON.parse(decodeURIComponent(option.thecard))
    energy_info.value = JSON.parse(option.energy_info)
    if (haveDraw.value) {
      for (let i = 0; i < haveDraw.value.length; i++) {
        const rule_id = haveDraw.value[i].rule_id
        if (rule_id == 1 || rule_id == 2) {
          wxvibrateLong(rule_id)
          rewardVideo.value = `https://ojqn.wm2177.com/wechat_imgs/${
            rule_id == 1 ? 'drawvideo' : 'smallvideo'
          }.mp4`
          if (userCodeStore.usercode.animation == 1) {
            showvideo.value = true
          }
          return
        }
      }
    }
  })
  // onUnload(() => {
  //   console.log(122)
  //   clearInterval(switchTimer)
  //   clearInterval(gamingTimer)
  // })
  onHide(() => {
    uni.$off('thecoupon')
  })
  let switchTimer = null
  let gamingTimer = null
  const switchNum = ref(0)
  const gamingNum = ref(0)
  const game_id = ref('')
  const gameStatus = ref()
  function switchFun() {
    switchTimer = setInterval(() => {
      switchNum.value = (switchNum.value - 1).toFixed(0)
      if (switchNum.value < 1) {
        clearInterval(switchTimer)
      }
    }, 1000)
  }
  function gamingFun() {
    gamingTimer = setInterval(() => {
      gamingNum.value = (gamingNum.value - 1).toFixed(0)
      if (gamingNum.value < 1) {
        clearInterval(gamingTimer)
      }
    }, 1000)
  }

  function togold() {
    clearInterval(gamingTimer)
    clearInterval(switchTimer)
    uni.navigateTo({
      url: `/drawPage/goldDraw/index?game_id=${game_id.value}&box_id=${boxId.value}`,
    })
  }
  onUnload(() => {
    clearInterval(gamingTimer)
    clearInterval(switchTimer)
  })
  const switchState = ref(0)
  const percent = ref(0)
  const hasFeed = ref(false)
  function boxMineDetail() {
    __Api.boxMineDetail({ box_id: boxId.value, is_own: 1 }).then((res) => {
      if (res.st.game) {
        clearInterval(gamingTimer)
        clearInterval(switchTimer)
        const obj = res.st
        gameStatus.value = obj.game.status
        game_id.value = obj.game.game_id
        percent.value = +obj.process.percent
        switchState.value = obj.game.switch
        hasFeed.value = true
        if (obj.game.switch == 1) {
          // 状态:0=待开始,1=进行中,2=已完成,-1=已超时
          if (gameStatus.value == 0) {
            switchNum.value = +obj.game.in_seconds_cutdown
            switchFun()
          }
          if (gameStatus.value == 1) {
            gamingNum.value = +obj.game.game_seconds_cutdown
            gamingFun()
          }
        }
      } else {
        hasFeed.value = false
      }
    })
  }
  onShow(() => {
    boxMineDetail()
    uni.$once('thecoupon', (data) => {
      // console.log(data)
      realmoney.value = paymoney.value
      if (data.coupon) {
        couponId.value = data.coupon.id
        couponname.value = data.coupon.title
        // 满减
        if (data.coupon.type == 1) {
          realmoney.value = Number(
            (paymoney.value - data.coupon.money).toFixed(2)
          )
        } else if (data.coupon.type == 2) {
          realmoney.value = Number(
            (paymoney.value - data.coupon.money).toFixed(2)
          )
        } else if (data.coupon.type == 3) {
          realmoney.value = Number(
            (paymoney.value * data.coupon.discount).toFixed(2)
          )
        }
      }
    })
  })
  function saveImg() {
    uni.downloadFile({
      //下载
      url: 'https://ojqn.wm2177.com/apk/qrcode/wechatcode.jpg', //图片下载地址
      success: (res) => {
        if (res.statusCode === 200) {
          uni.saveImageToPhotosAlbum({
            //保存图片到系统相册。
            filePath: res.tempFilePath, //图片文件路径
            success: function () {
              uni.showToast({
                title: '图片保存成功',
                icon: 'none',
              })
            },
            fail: function (e) {
              console.log(e)
              uni.showToast({
                title: '图片保存失败,请截图',
                icon: 'none',
              })
            },
          })
        }
      },
    })
  }
</script>

<template>
  <view class="draw-video" v-if="showvideo">
    <video
      id="myVideo"
      :src="rewardVideo"
      autoplay="true"
      :controls="false"
      :enable-progress-gesture="false"
      :enable-play-gesture="false"
      :vslide-gesture="false"
      :vslide-gesture-in-fullscreen="false"
      :show-progress="false"
      @ended="showvideo = false"
    ></video>
    <view class="skipvideo" @click="showvideo = false"> </view>
  </view>
  <view class="cards-content" v-else-if="!showvideo">
    <view
      class=""
      v-if="hasFeed"
      style="position: absolute; left: 120rpx; top: 110rpx"
    >
      <Progress :percent="percent"></Progress>
    </view>
    <!-- <view class="congratulation"> </view> -->
    <view class="switchBox" v-if="switchState > 0" @click="togold()">
      <image
        src="https://ojqn.wm2177.com/wechat_imgs/gold/open.png"
        mode=""
      ></image>
      <view class="" style="font-size: 22rpx; color: red">
        剩余{{ gameStatus == 0 ? switchNum : gamingNum }}秒
      </view>
    </view>
    <image
      class="congratulation"
      src="https://ojqn.wm2177.com/wechat_imgs/newdesign/congratulation2.png"
      mode="widthFix"
    ></image>
    <view
      v-if="is_flip == 1"
      class=""
      style="
        width: 100%;
        font-size: 28rpx;
        text-align: center;
        margin-bottom: 10rpx;
      "
    >
      你可以选择翻开一张获得双倍奖励
    </view>
    <view class="cards">
      <!-- 单抽 -->
      <view v-if="cardsnum == 1" class="one-draw">
        <oneCard
          v-if="cardsnum == 1"
          :haveDraw="haveDraw"
          :secondShow="secondShow"
        ></oneCard>
      </view>
      <!-- 三抽 -->
      <view v-else-if="cardsnum == 3" class="three-draw">
        <threeCard
          v-if="cardsnum == 3"
          :haveDraw="haveDraw"
          :secondShow="secondShow"
        ></threeCard>
      </view>
      <!-- 十抽 -->
      <view v-else-if="cardsnum == 10" class="ten-draw">
        <tenCard
          v-if="cardsnum == 10"
          :haveDraw="haveDraw"
          :secondShow="secondShow"
          :is_flip="is_flip"
          :orderId="orderId"
          @canClickFun="canClickFun"
        ></tenCard>
      </view>
    </view>
    <view class="button-bottom 1111" v-if="canBack">
      <view class="button" @click="backto">
        <view v-if="energy_info && energy_info.img" class="energy_txt"
          >额外获得能量球：{{ energy_info.name }}
        </view>
        <image
          v-if="energy_info && energy_info.img"
          class="energy_img"
          :src="energy_info.img"
          mode=""
        ></image>
      </view>
      <view class="button" @click="payPOP"> </view>
    </view>

    <!-- 支付弹出层 -->
    <uni-popup ref="paypopup" type="bottom" @change="changePop">
      <PayBox
        v-if="!secondShow"
        :is_integral="is_integral == 2 ? true : false"
        :couponname="couponname"
        :createOrderUrl="createOrderUrl"
        :realmoney="realmoney"
        :paymoney="paymoney"
        :couponId="couponId"
        :buyCount="cardsnum"
        :blindboxId="boxId"
        @payReturnFun="payReturnFun"
        @chooseCoupon="chooseCoupon"
        :boxDetailInfo="{
          img: drawImg,
          name: drawName,
          pay_type: is_integral,
          goodsPay: { img: payGoodImg, id: payGoodId },
        }"
      ></PayBox>
    </uni-popup>
    <!-- 实名制出层 -->
    <uni-popup ref="namepopup" type="center">
      <!--  -->
      <view class="namepopup-content 1" v-if="shebei == 'mp-weixin'">
        <view class="namepopup-title"> 提示 </view>
        <view class="namepopup-content-tow">
          鉴于您是平台的优质用户，为了能给您提供更好的服务体验，请先完成实名制认证。</view
        >
        <view class="namepopup-button">
          <view class="" @click="namepopup.close('center')"> 再想一下 </view>
          <view class="" @click="goRealName"> 确认实名 </view>
        </view>
      </view>
      <view class="namepopup-content 2" v-else>
        <view class="namepopup-title"> 提示 </view>
        <view class="namepopup-content-tow">
          鉴于您是平台的优质用户，请前往微信小程序，搜索 欧魂online
          进行实名制认证。</view
        >
        <view
          class=""
          style="display: flex; justify-content: center; margin-bottom: 40rpx"
        >
          <image
            style="width: 160rpx; height: 160rpx"
            src="https://ojqn.wm2177.com/apk/qrcode/wechatcode.jpg"
            mode="widthFix"
          ></image>
        </view>
        <view class="namepopup-button">
          <view @click="saveImg">保存二维码</view>
          <view class="" @click="namepopup.close('center')"> 我知道了 </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<style lang="scss" scoped>
  // 卡片背景

  .second-scroll {
    // animation: scroll-left 1s ease-out forwards;
  }

  @keyframes displayTop {
    from {
      opacity: 0;
      // display: none;
    }
    to {
      opacity: 1;
      // display: block;
    }
  }

  .draw-video {
    position: relative;
    height: 100vh;
    width: 100%;
    video {
      height: 100%;
      width: 100%;
    }
    .skipvideo {
      width: 215rpx;
      height: 65rpx;
      background: url('https://ojqn.wm2177.com/wechat_imgs/skipvideo.png')
        no-repeat;
      background-size: contain;
      position: absolute;
      top: 200rpx;
      right: 0;
    }
    ::v-deep #myVideo::-webkit-media-controls {
      display: none !important;
    }
  }
  .cards-content {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    height: 100vh;
    width: 100%;
    padding-top: 170rpx;
    padding-bottom: 100rpx;
    box-sizing: border-box;
    background-image: linear-gradient(
      to bottom,
      #f8ec8a 1%,
      #f9ed8b 5%,
      #ffefff 36%,
      #eaf7ff 70%,
      #ffffff 100%
    );
    // background: url('https://ojqn.wm2177.com/wechat_imgs/newdesign/cards-bg2.png')      no-repeat;
    background-size: 100%;
    .switchBox {
      position: absolute;
      width: 120rpx;
      height: 120rpx;
      text-align: center;
      top: 180rpx;
      left: 20rpx;
      image {
        width: 100%;
        height: 100%;
        display: inline-block;
      }
    }
    .congratulation {
      height: auto;
      width: 600rpx;
      // animation: scroll-left 1s ease-out forwards;
    }
    .cards {
      flex: 1;
    }
    .button-bottom {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 98rpx;
      .energy_txt {
        text-align: center;
        width: 100%;
        position: absolute;
        top: 80rpx;
        font-size: 26rpx;
        color: #902500;
      }
      .energy_img {
        position: absolute;
        font-weight: 900;
        text-align: center;
        width: 80rpx;
        height: 80rpx;
        position: absolute;
        top: -20rpx;
        left: -20rpx;
      }
      .button {
        height: 100%;
        width: 302rpx;
        font-size: 38rpx;
        font-weight: 900;
        text-align: center;
        line-height: 90rpx;
        position: relative;
        &:first-child {
          background: url('https://ojqn.wm2177.com/wechat_imgs/newdesign/btn-left2.png')
            no-repeat;
          background-size: contain;
          margin-right: 50rpx;
          color: #000;
        }
        &:last-child {
          background: url('https://ojqn.wm2177.com/wechat_imgs/newdesign/btn-right2.png')
            no-repeat;
          background-size: contain;
          color: #000;
        }
      }
    }
    .paypopup-content {
      display: flex;
      flex-direction: column;
      align-items: center;
      height: 707rpx;
      padding: 30rpx 30rpx 0 30rpx;
      box-sizing: border-box;
      // background-color: rgba(26, 19, 63, 0.9);
      background-image: linear-gradient(180deg, #fbf7e7, #fff6a8, #fbf7e4);
      color: #3d3d3d;
      .top-boxinfo {
        width: 100%;
        display: flex;
        align-items: center;
        flex-shrink: 0;
        .boxinfo-left {
          width: 184rpx;
          height: 184rpx;
          border-radius: 6rpx;
          overflow: hidden;
          margin-right: 12rpx;
        }
        .boxinfo-right {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          height: 180rpx;
        }
      }
      .choose-coupon {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-top: 47rpx;
        flex-shrink: 0;
      }
      .pays {
        width: 100%;
        .pays-title {
          margin: 24rpx 0 13rpx 0;
          font-size: 24rpx;
        }
        .radio-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 13rpx 0;

          border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
          &:last-child {
            border: none;
          }
          .radio-item-left {
            display: flex;
            align-items: center;
          }
        }
      }
      .paybutton {
        width: 100%;
        height: 109rpx;
        margin-top: 32rpx;
        background: url('https://ojqn.wm2177.com/wechat_imgs/newdesign/paybutton3.png')
          no-repeat;
        background-size: contain;
        font-weight: 800;
        font-size: 38rpx;
        color: #1f1f1f;
        line-height: 96rpx;
        text-align: center;
        // text-stroke: 1rpx #FFFFFF;
        // -webkit-text-stroke: 1rpx #FFFFFF;
      }
      .pays-agree {
        width: 100%;
        margin-top: 29rpx;
        font-size: 20rpx;
        color: #3d3d3d;
        text-align: center;
      }
    }
  }
  .namepopup-content {
    width: 600rpx;
    // height: 404rpx;
    padding: 10px 30rpx;
    box-sizing: border-box;
    border-radius: 36rpx;
    background-color: #fff;
    .namepopup-title {
      height: 114rpx;
      border-bottom: 1px solid #d8d8d8;
      text-align: center;
      font-size: 40rpx;
      line-height: 114rpx;
      color: black;
    }
    .namepopup-content-tow {
      height: 164rpx;
      padding-top: 32rpx;
      box-sizing: border-box;
      text-align: center;
      font-size: 28rpx;
      color: #9b9b9d;
    }
    .namepopup-button {
      display: flex;
      align-items: center;
      justify-content: space-between;
      color: white;
      // margin-top: 26rpx;
      view {
        width: 234rpx;
        height: 80rpx;
        background-color: $all-color;
        border-radius: 40rpx;
        text-align: center;
        font-size: 26rpx;
        font-weight: 700;
        line-height: 80rpx;
        &:first-child {
          border: 2rpx solid $all-color;
          background-color: #fff;
          color: $all-color;
        }
      }
    }
  }
</style>
